package com.cw.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cw.common.Constants;
import com.cw.common.R;
import com.cw.config.JwtConfig;
import com.cw.entity.Employee;
import com.cw.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Objects;


@Slf4j
@RestController
@RequestMapping("/employee")
@CrossOrigin
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * @param employee
     * @param response
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpServletResponse response){
        //1、密码加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2.判断用户名是否存在    3.判断密码
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getAccountName,employee.getAccountName()).eq(Employee::getPassword,password);
        Employee one = employeeService.getOne(wrapper);
        HashMap<String, Object> map = new HashMap<>(16);
        if (BeanUtil.isEmpty(one)){
            map.put("access_token", "INVALID_PARAMETER");
            return R.success(map);
        }
        //4.判断员工状态是否禁用
        if (one.getStatus()==0){
            log.info("当前状态不可用");
            map.put("access_token", "THE_CURRENT_STATE_CANNOT_BE_USED");
            return R.success(map);
        } else {
            // 生成令牌,将令牌写入响应头
            DateTime now = DateTime.now();
            DateTime dateTime = now.offsetNew(DateField.SECOND, 5);
            //签发时间
            map.put(JWTPayload.ISSUED_AT,now);
            //过期时间
            map.put(JWTPayload.EXPIRES_AT,dateTime);
            //生效时间
            map.put(JWTPayload.NOT_BEFORE,now);
            map.put("current_id", one.getId());
            String token = JWTUtil.createToken(map, Constants.SECRET_KEY.getBytes(StandardCharsets.UTF_8));
            log.info("生成的token{}",token);
            //5.将员工id存入redis中，返回成功结果
            this.redisTemplate.opsForHash().put("EMP",one.getId(),one);
            response.setHeader("Authorization",token);
            log.info("添加到Redis成功");
        }
        //6.响应给前台
        return R.success(one);
    }
    /**
     * 登出功能
     * @param
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpServletRequest request){
        String access_token = request.getHeader("Authorization");
        JWT jwt = JWTUtil.parseToken(access_token);
        boolean verify = JWTUtil.verify(access_token,Constants.SECRET_KEY.getBytes(StandardCharsets.UTF_8));
        this.redisTemplate.opsForHash().delete("EMP",Long.valueOf(jwt.getPayload("current_id").toString()));
        return R.success(verify);
    }


    /**
     * 新增操作
     * @return
     */
    @PostMapping
    public R save(@RequestBody Employee employee,HttpServletRequest request){

        if (!JwtConfig.getCurrentId(request).equals(Constants.ADMIN_ID)){
            Employee emp=(Employee)this.redisTemplate.opsForHash().get("EMP",JwtConfig.getCurrentId(request));
            assert emp != null;
            employee.setWindowId(emp.getWindowId());
        }
        //获取页面的数据
        log.info("添加到的数据{}",employee);
        employee.setPassword(DigestUtils.md5DigestAsHex("111111".getBytes(StandardCharsets.UTF_8)));

        employee.setStatus(1);

        boolean save = employeeService.save(employee);

        return save?R.success(null):R.error("添加失败");
    }

    /**
     * 员工信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(@RequestParam(name = "page") Integer page,
                        @RequestParam(name = "pageSize") Integer  pageSize,
                        @RequestParam(name = "name",required = false) String name ){
        log.info("page={},pageSize={},name={}",page,pageSize,name);
        //1.创建分页构造器
        Page pageInfo = new Page(page, pageSize);
        //2.创建条件构造器
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper();
        //3.过滤条件
        wrapper.like(name!=null,Employee::getName,name);
        //4.添加排序条件
        wrapper.orderByDesc(Employee::getUpdateTime);
        //5.重新查询
        employeeService.page(pageInfo,wrapper);

        return R.success(pageInfo);
    }

    /**
     * 修改状态
     * @param employee
     * @return
     */
    @PutMapping
    public R update(@RequestBody Employee employee,HttpServletRequest request){
        //1.接收参数
        log.info("修改的emp为{}",employee);
        String password = this.employeeService.getById(employee.getId()).getPassword();
        //2.维护字段，修改人，修改时间
        if (StrUtil.isNotEmpty(employee.getPassword()) &&!Objects.equals(password,employee.getPassword())){
            employee.setPassword(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes(StandardCharsets.UTF_8)));
        }
        //3.修改（状态会通过前台传到后台）
        boolean b =false;
        if (JwtConfig.getCurrentId(request).equals(Constants.ADMIN_ID)||JwtConfig.getCurrentId(request).equals(employee.getId())){
            b=employeeService.updateById(employee);
        }
        return  b?R.success("操作成功"):R.error("操作失败");
    }

    /**
     * 查询员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public  R  updateStaff(@PathVariable() Long id){
        log.info("获取到的id{}",id);
        Employee byId = employeeService.getById(id);
        if (byId!=null ){
            return R.success(byId);
        }
        return R.error("用户不存在");
    }



}
